package org.zjt.demo.elasticsearch;

import org.apache.log4j.Logger;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.sort.SortParseElement;
import java.net.InetAddress;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;

/**
 * Created by zhang on 2017/3/3.
 */
public class DeleteDocument {
    private static final Logger logger = Logger.getLogger(DeleteDocument.class);
    public static void main (String []agre) throws Exception {
        TransportClient client = TransportClient.builder().build()
                .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
        //匹配所有 Scroll便利数据 每次读取1000条 while循环中 会重新拉取数据 大数据建议用Scroll
        QueryBuilder qb = matchAllQuery();
        SearchResponse response = client.prepareSearch("hotelindex")
                .setTypes("poidata")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .addSort(SortParseElement.DOC_FIELD_NAME, SortOrder.ASC)
                .setScroll(new TimeValue(60000))
                .setQuery(qb)
                .setFrom(0)
                .setSize(50)
                .execute()
                .actionGet();

        long count =response.getHits().getTotalHits();
        while (true) {
            for (SearchHit hit : response.getHits().getHits()) {
                client.prepareDelete(hit.getIndex(),hit.getType(),hit.getId()).get();
            }
            try {
                response = client.prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(60000)).execute().actionGet();
                //Break condition: No hits are returned
                if (response.getHits().getHits().length == 0) {
                    break;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
